import axios from 'axios';
import zx_njia from './ningjia';
import {showLoading, hideLoading} from "../../utils/loading";
import {Toast} from '../../utils/toast.js';
import {reFreshUserInfo} from '../../utils/WXH/login.js';
import updateAddress from "../../utils/updateAddress.js"
//import {NJ} from "../config";
export default {
    namespaced: true,
    state: {
		addressList:[], //收货地址信息
		addressNow:{},//当前的地址信息
		userInfo:{},  //nj用户登录信息
		addFlag:true, //true是新增
		addressDetail:'', // 确认订单页面存入 并取用
		mynode:'',    // 确认订单页面存入 并取用  卖家留言
		timeNormal:null, //确认订单页面常规商品时间
		timeBig:null,  //确认订单页面大件商品配送时间
		dateNormal:null, // 确认订单页面常规商品日期
		dateBig:null,// 确认订单页面大件商品日期
		normalM:null,   //常规的运费
        bigM:null,   //大件的运费
        fpObj:{},  //订单页面发票信息
        ticketList:[],   //优惠券列表 ，用于发送下单请求
        chooseTicketFlag:false, // 是否选择优惠券并调用接口重新获取金额
        deliveryType:null,// 订单页面物流方式
        ladderIdList:[],  // 购物车活动   用于下单请求接口
        giftVOList:[],  // 购物车活动   用于下单请求接口
        giftSendArr:[], // 含有赠品的活动信息，用于展示赠品信息
        useGiftCard:false, // 是否使用钱包支付
        storeNow:null,  // 当前门店对象 个人中心门店
        isShow:false,   // 头部列表显示隐藏
        homeStoreNow:null, //首页推荐门店
        homeAddressNow:null, // 首页用户登陆后选择的地址  （推荐门店，订单默认选址）  目前弃用
        availAmount:0,   //用户钱包可用余额
        showMask:false,  // 钱包支付是否需要填密碼
        useMapFlag:3 , // 首页门店获取定位标志  是否在定位中
        addAddressHome:null, // 用户补充或更改地址信息
        chooseAddressActiveIndex:null,  // 首页选择地址激活下标
        token:null, // calOrder接口存的 用于下单时后台辨识
        orderFlag:false, // 用于判断订单页面其它接口信息是否返回，如果没有返回就不让用户点击提交订单按钮
        allMoney:{},  // 订单页面用于缓存金额信息
        fpInfo:null,   // 存所有发票信息
        feedBackInfo:{}, // 存意见反馈信息 避免需要用户重复输入
        timeSaveObj:null, // 存用户选择配送时间的数据
        confrimOrderRes:{} //存订单页面获取信息接口所有数据 供页面跳转后用 （缓存）

    },
    getters: {
    	//判斷是編輯還是新增
    	getaddFlag(state){
			console.log('================',state.addFlag);
			return state.addFlag;
		},
    	//获取地址列表信息
		getAddressList(state){
//			console.log('================',state.addressList);
			return state.addressList;
		},
		//获取用户信息
		getUserInfo(state){
//			console.log('================get',state.userInfo);
			return state.userInfo;
		},
		getNowAddress(state){
//			console.log('================get',state.userInfo);
			return state.addressNow;
		},
		getAddressDetail(state){
//			console.log('================get',state.userInfo);
			return state.addressDetail;
		},
		getMynode(state){
//			console.log('================get',state.userInfo);
			return state.mynode;
		},
		getTimeNormal(state){
			return state.timeNormal;
		},
		getTimeBig(state){
			return state.timeBig;
		},
		getNormalM(state){
			return state.normalM;
		},
		getDateNormal(state){
			return state.dateNormal;
		},
		getDateBig(state){
			return state.dateBig;
		},
		getBigM(state){
			return state.bigM;
		},
		getFpObj(state){
			return state.fpObj;
		},
		getToken(state){
			return state.token;
		},
		getTicketList(state){
			return state.ticketList;
		},
		getDeliveryType(state){
			return state.deliveryType;
		},
		getLadderIdList(state){
			return state.ladderIdList;
		},
		getGiftVOList(state){
			return state.giftVOList;
		},
		getUseGiftCard(state){
			return state.useGiftCard;
		},
		getGiftSendArr(state){
			return state.giftSendArr;
		},
		getStoreNow(state){
			return state.storeNow;
		},
		getIsShow(state){
			return state.isShow;
		},
		getHomeStoreNow(state){
			return state.homeStoreNow;
		},
		getHomeAddressNow(state){
			return state.homeAddressNow;
		},
		getAvailAmount(state){
			return state.availAmount;
		},
		getShowMask(state){
			return state.showMask;
		},
		getUseMapFlag(state){
			return state.useMapFlag;
		},
		getChooseAddressActiveIndex(state){
			return state.chooseAddressActiveIndex;
		},
		getOrderFlag(state){
			return state.orderFlag;
		},
		getAllMoney(state){
			return state.allMoney;
		},
		getFpInfo(state){
			return state.fpInfo;
		},
		getFeedBackInfo(state){
			return state.feedBackInfo;
		},
		getTimeSaveObj(state){
			return state.timeSaveObj;
        },
        getConfrimOrderRes(state){
            return state.confrimOrderRes;
        }
    },
    actions: {

		//请求用户信息接口   传入的对象有 域名属性  sessionid
		addressGetUser({commit,state},sessionid) {
//			receivername
//			console.log(window.api.base_host,'获取session1****************************');
			let time = new Date().getTime();
			let sessionId = localStorage.getItem('sessionId');
//			http://172.19.5.89:33004/customer/refreshUserInfo
//			http://172.19.6.152/customer/refreshUserInfo
//          let url = window.api.local_host+'/user/getUserInfo?token='+time; //erp的接口
            let url = window.api.customer_host+'/customer/getCustomer?token='+time;
            showLoading();
			let config = {
				url: url,
				method:'get',
				headers: {'sessionId': sessionId, 'Content-Type':'application/json', 'Accept' : 'application/json'},
			}
			try {
				axios(config).then((res)=>{
//					console.log(res.status,res.data.data[0].addressList,'ssss');
					hideLoading();
					let data = res.data.data[0];
					let addressArr = data.addressLists;
	//				console.log(data,'||||||||||');
					let defaultAddress = data.addressLists;
					let arr = [];
					let storeAddress = [];


					//过滤地址信息
					var arrStoreList = this.getters["qxz/getStoreList"];
					var arrStore = [];
					for(let j = 0; j < arrStoreList.length; j++){
						arrStore.push(arrStoreList[j].storeCode);
					}
					console.log(arrStore,'门店列表')
					//过滤地址信息	暂时注释
//					var newArrAddressList = [];
//					for(let i = 0; i < addressArr.length; i++){
//					     var index = arrStore.indexOf(addressArr[i].storeCode);
//					     console.log(index,'是否存在');
//					     if(index != -1){
//					     	newArrAddressList.push(addressArr[i]);
//					     }
//					}
//					addressArr = newArrAddressList;
					//过滤地址信息
					data.addressList = addressArr;
					commit('setAddressListMutation',arr);
					commit('setUseInfoMutation',data);
					commit('setAddressListMutation',addressArr);
				})
			}catch(err){
				hideLoading();
				console.log(err);
			}

        },
        //快速增加地址的方法快速增加地址的方法
        addAddressQuicker({commit,state},obj){
        	console.log(obj,'快速增加  参数');
        	if(obj){
        		var provinceId = null;
//      		http://172.19.5.89:33001/address/select/1
//				let url = window.api.mall_base_host + '/address/getarealist?areaid='+ 1  //erp的接口
				var url = window.api.base_host+'/address/select/';
		        axios.get(url + 1).then((res)=>{

		        	var province = res.data.data;
		        	for(let i = 0; i < province.length; i++){

		        		if(obj.province == province[i].name){
//		        			console.log(province[i].rid,'province[i].name')
		        			var provinceId = province[i].rid;
		        			axios.get(url + province[i].rid).then((res)=>{
		        				var city = res.data.data;
		        				for(let j = 0; j < city.length; j++){
		        					if(obj.city === city[j].name){
//		        						console.log(city[j].rid,'city[j].name');
		        						var cityId = city[j].rid;
		        						axios.get(url + city[j].rid).then((res)=>{
		        							var region = res.data.data;
		        							for(let k = 0 ;k < region.length; k++){
		        								if(obj.region === region[k].name){
//		        									console.log(region[k].rid,'region[k].name');
		        									var regionId = region[k].rid;
		        									let info = this.state.wxh.userInfo;
		        									console.log(info,'用户信息')
		        									let sex;
		        									if(info.sex === "男" || info.sex === ""){
		        										sex = "0"
		        									} else if (info.sex === "女") {
		        										sex = "1";
		        									}
//

		        									var params = {
		        										address:obj.address,
														city:cityId,
														defaultaddress:"1",
//														enterpriseid:window.api.enterpriseCode,
														label:"1",
														phone:info.mobile,
														province:provinceId,
														receivername:info.vipname,
														positionlat:obj.positionlat,
														positionlng:obj.positionlng,
														region:regionId,
														sex,
														type:"ADD",
														result:obj.province + " " + obj.city + " " + obj.region + " " + obj.address,
														component:obj.component
		        									}
//		        									console.log("这是快速添加address的params", params);
//
		        									this._actions["zx/setAddressInfo"][0](params);
		        								}
		        							}
		        						})
		        					}
		        				}
		        			})
		        		}
		        	}
		        })

        	}
        },
        //设置地址信息接口
        setAddressInfo({commit,state},params){
//      	console.log(params,'params');
//			console.log(this.getters["qxz/getLocation"],'齐兴志的....')

			console.log(params.component,'这是组件this')
			var component = params.component;  // 存组件信息用于刷新用户中心信息

			var addressDetail = params.address;
			if(params.address && params.address.length > 100){
				params.address = String(params.address).substring(0,100);
			}
			let info = this.state.wxh.userInfo;
        	params.userid = info.userid;

//      	console.log(window.api.enterpriseCode,'企业参数')
        	params.enterprisecode = window.api.enterpriseCode;
			params.receivername = params.receivername;
			delete params.flag;
			delete params.component;
//			delete params.receivername;
        	if(params.type == "ADD"){
				params.storeCode = localStorage.getItem('storeCode');  // 将收获地址与门店关联
        		delete params.addressId;
        	}
        	var showToast = true;
        	if(params.type == "UPDATE"){
        		showToast = params.showToast;
        		delete params.isNew;
        		delete params.showToast;
        	}
//      	console.log("--------------showToast----------",showToast)
			var sessionId = localStorage.getItem('sessionId');
			let config = {
				url: window.api.customer_host+'/address',
				method:'POST',
				data:params,
				headers: {'sessionId': sessionId, 'Content-Type':'application/json', 'Accept' : 'application/json'},
			}
			console.log('增加地址开始调用接口11111')
        	axios(config).then((res) => {
//      		console.log(JSON.stringify(params),'收货地址入参')
				//收货地址操作校验开始
//				console.log("--------------showToast----------",showToast)
				if(params.type == "ADD" && res.data.returnCode == 1){
					updateAddress(res.data.data);//更新qxz的保存location的值
					Toast({
			            message: "收货地址添加成功",
			            iconClass: "aui-iconfont aui-icon-correct",
			            duration: 2000,
			            type: 'success'
		            });
				}else if(params.type == "ADD" && res.data.returnCode == 0){
					Toast({
			            message: res.data.msg,
			            duration: 2000,
			            type: 'fail'
		          	})
				}

				if(params.type == "UPDATE" && res.data.returnCode == 1 && showToast){
					console.log("魔战无双")
					updateAddress(res.data.data);//更新qxz的保存location的值
					Toast({
			            message: "收货地址编辑成功",
			            iconClass: "aui-iconfont aui-icon-correct",
			            duration: 2000,
			            type: 'success'
		            });
				}else if(params.type == "UPDATE" && res.data.returnCode == 0 && showToast){
					Toast({
			            message: '收货地址编辑失败',
			            duration: 2000,
			            type: 'fail'
		          	})
				}

				if(params.type == "DEL" && res.data.returnCode == 1){
					Toast({
			            message: "收货地址删除成功",
			            iconClass: "aui-iconfont aui-icon-correct",
			            duration: 2000,
			            type: 'success'
		            });
				}else if(params.type == "DEL" && res.data.returnCode == 0){
					Toast({
			            message: '收货地址删除失败',
			            duration: 2000,
			            type: 'fail'
		          	})
				}
//				console.log(params.type,'用户操作收货地址');
				
				// updateAddress()
				reFreshUserInfo(component); // 调用个人中心刷新用户信息接口

				console.log('增加地址结束调用用户接口开始22222');

				//收货地址操作校验结束//收货地址操作校验结束
				let time = new Date().getTime();
	  			let url = window.api.customer_host+'/customer/getCustomer?token='+time;
	  			let sessionId = localStorage.getItem('sessionId');
	  			let config = {
					url: url,
					method:'get',
					headers: {'sessionId': sessionId, 'Content-Type':'application/json', 'Accept' : 'application/json'},
				}
//	            axios(config).then((data)=>{
////	            	console.log(params.defaultaddress,'默认地址是否改变')
//	            	commit('setUseInfoMutation',data.data.data[0]);
//
//					let arr = [];
//					let storeAddressArr = [];
//
//					let addressArr = data.data.data[0].addressLists;
//
//					console.log('增加地址获取到用户信息33333',data.data.data[0]);
//					//过滤地址信息
//					var arrStoreList = this.getters["qxz/getStoreList"];
//					var arrStore = [];
//					for(let j = 0; j < arrStoreList.length; j++){
//						arrStore.push(arrStoreList[j].storeCode);
//					}
//					//过滤地址信息	暂时注释
////					var newArrAddressList = [];
////					for(let i = 0; i < addressArr.length; i++){
////					     var index = arrStore.indexOf(addressArr[i].storeCode);
////					     console.log(index,'是否存在');
////					     if(index != -1){
////					     	newArrAddressList.push(addressArr[i]);
////					     }
////					}
////					addressArr = newArrAddressList;
//					//过滤地址信息
//					commit('setAddressListMutation',arr);
//		 			commit('setAddressListMutation',addressArr);
//	            })
        	})
        }


    },
    mutations: {
		setUseInfoMutation(state,data){
			state.userInfo = Object.assign({}, state.userInfo, data);
//			state.userInfo = data;
		},
		setAddressListMutation(state,data){
			state.addressList = data;
//			console.log(state.addressList,'state.addressList这是测试打印');
		},
		//整体设置当前地址
		setNowAddressMutation(state,addNow){
			state.addressNow = addNow;
		},
		//个别改变当前地址
		setNowAddressMutationSinger(state,addNowSinger){
//			console.log('result',addNowSinger)
			for(let i in state.addressNow){
				for(let j in addNowSinger){
					if(i == j){
//						console.log('result',addNowSinger)
						state.addressNow[i] = addNowSinger[i];
					}
				}
			}
		},
		//設置是否為編輯
		setaddFlagMutation(state,flag){
			state.addFlag = flag;
//			console.log(state.addFlag)
		},
		setAddressDetail(state,addressDetail){
			state.addressDetail = addressDetail;
//			console.log(state.addressDetail)
		},
		setMynode(state,mynode){
			state.mynode = mynode;
//			console.log(state.mynode)
		},
		setTimeNormal(state,timeNormal){
			state.timeNormal = timeNormal;
			console.log(new Date(state.timeNormal.startBookTm),'1111111')
			console.log(new Date(state.timeNormal.endBookTm),'1111111')
		},
		setTimeBig(state,timeBig){
			state.timeBig = timeBig;
			console.log(state.timeBig,'222222')
		},
		setDateNormal(state,dateNormal){
			state.dateNormal = dateNormal;
		},
		setDateBig(state,dateBig){
			state.dateBig = dateBig;
		},
		setNormalM(state,normalM){
			console.log('仅仅22')
//			state.normalM = Object.assign({}, normalM);
			state.normalM = normalM;
//			console.log(state.normalM,'state.normalM')
		},
		setBigM(state,bigM){
			state.bigM = bigM;
//			console.log(state.bigM,'state.bigM')
		},
		setFpObj(state,fpObj){
			state.fpObj = fpObj;
		},
		setTicketList(state,ticketList){
			state.ticketList = ticketList;
//			console.log(state.ticketList,'state.ticketList')
		},
		setDeliveryType(state,deliveryType){
			state.deliveryType = deliveryType;
		},
		setLadderIdList(state,ladderIdList){
			state.ladderIdList = ladderIdList;
		},
		setGiftVOList(state,giftVOList){
			state.giftVOList = giftVOList;
		},
		setUseGiftCard(state,useGiftCard){
			state.useGiftCard = useGiftCard;
		},
		setToken(state,token){
			state.token = token;
		},
		setGiftSendArr(state,giftSendArr){
//			console.log(giftSendArr,'******************************************************************************************8')
			return state.giftSendArr = giftSendArr;
		},
		setStoreNow(state,store){
//			console.log("****----***")
			state.storeNow = store;
		},
		setIsShow(state,isShow){
			state.isShow = isShow;
		},
		setHomeStoreNow(state,homeStoreNow){

			state.homeStoreNow = homeStoreNow;
			console.log('设置门店',state.homeStoreNow)
		},
		setHomeAddressNow(state,homeAddressNow){
			state.homeAddressNow = homeAddressNow;
//			console.log(state.homeAddressNow,'vuex')
		},
		setAvailAmount(state,availAmount){
			state.availAmount = availAmount;
		},
		setShowMask(state,showMask){
			state.showMask = showMask;
		},
		setUseMapFlag(state,useMapFlag){
			state.useMapFlag = useMapFlag;
		},
		setAddAddressHome(state,address){
			state.addAddressHome = address;
		},
		setChooseAddressActiveIndex(state,activeIndex){
			state.chooseAddressActiveIndex = activeIndex;
		},
		setOrderFlag(state,flag){
			state.orderFlag = flag;
		},
		setAllMoney(state,money){
			state.allMoney = money;
		},
		setFpInfo(state,fp){
			state.fpInfo = fp;
		},
		setFeedBackInfo(state,feedBackInfo){
			state.feedBackInfo = feedBackInfo;
		},
		setTimeSaveObj(state,timeSaveObj){
			state.timeSaveObj = timeSaveObj;
        },
        setConfrimOrderRes(state,obj){
            state.confrimOrderRes = obj;
        }
    },
    modules: {
    	"NJ": zx_njia
    }
}
